package manage.actions.worker;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import manage.actions.ManageAction;
import manage.commons.annontations.AccessControl;
import manage.commons.annontations.AccessVerify;
import manage.commons.annontations.RequiredLogin;
import manage.commons.utils.CommonUtil;
import manage.commons.utils.DateUtil;
import manage.commons.utils.EncryptUtils;
import manage.commons.utils.InputStreamUtil;
import manage.commons.utils.Pager;
import manage.modules.dept.service.DeptService;
import manage.modules.group.service.GroupService;
import manage.modules.worker.model.Worker;
import manage.modules.worker.service.WorkerService;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.util.CollectionUtils;

@RequiredLogin
@AccessVerify
public class WorkerAction extends ManageAction {

	private static final long serialVersionUID = -8894846958924131787L;
	private WorkerService workerService;
	private DeptService deptService;
	private GroupService groupService;
	private Pager<Worker> pager = new Pager<Worker>(100);
	private Worker worker;
	private InputStream inputStream;
	private Map<String, String> param;
	private String[] groupIds;

	@Override
	@AccessControl
	@Action("worker-input")
	public String input() {
		getRequest().setAttribute("allDept", deptService.listAll());
		getRequest().setAttribute("allGroup", groupService.listAll());
		return SUCCESS;
	}

	@AccessVerify(-1)
	@Action(value = "worker-addorupdate", results = { @Result(name = SUCCESS, location = "/worker/worker-form.jsp") })
	public String forwardAddOrUpdatePage() {
		if (isAddOperater()) {
			action = "/worker/worker-add.do";
			request.setAttribute("btnKeyWord", "添加员工");
			request.setAttribute("groups", groupService.listAll());
		} else if (isUpdateOperater()) {
			action = "/worker/worker-edit.do";
			request.setAttribute("btnKeyWord", "更新员工信息");
			request.setAttribute("groups", groupService.listAll());
			request.setAttribute("mygroups", workerService
					.listGroupIdByWorkerId(currentWorker.getWorkerId()));
			worker = workerService.select(worker.getWorkerId());
		}
		return SUCCESS;
	}

	@AccessControl
	@Action(value = "worker-query", results = { @Result(name = SUCCESS, location = "/worker/worker-list.jsp") })
	public String query() {
		workerService.query(param, pager);
		pager.pagerUtils(pager, getRequest());
		return SUCCESS;
	}

	@AccessVerify(-1)
	@Action(value = "worker-select", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "worker" }) })
	public String select() {
		if (null != worker && null != worker.getWorkerId()) {
			boolean exists = workerService.exists(worker.getWorkerId());
			if (exists) {
				worker = workerService.select(worker.getWorkerId());
			}
		}
		return SUCCESS;
	}

	@AccessVerify(-1)
	@Action(value = "current-worker", results = { @Result(name = SUCCESS, type = "json", params = {
			"root", "worker" }) })
	public String selectCurrentWorker() {
		worker=workerService.select(currentWorker.getWorkerId());
		return SUCCESS;
	}

	@Action(value = "worker-add", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "text/plain; charset=utf-8", "inputName",
			"inputStream" }) })
	public String add() throws Exception {
		if (null != worker && null != worker.getWorkerId()
				&& worker.getWorkerName() != null && null != worker.getEmail()) {
			boolean exists = workerService.exists(worker.getWorkerId());
			if (!exists) {
				worker.setCreateTime(DateUtil.getCurrentDateTime());
				String passwd = worker.getPassword();
				if (StringUtils.isNotBlank(passwd)) {
					worker.setPassword(EncryptUtils.encryptPwd(passwd));
				}
				int count = workerService.insert(worker);
				if (count == 1) {
					if (ArrayUtils.isNotEmpty(groupIds)) {
						workerService.insertWorkerOfGroups(
								worker.getWorkerId(),
								CommonUtil.evalStringArrayToLongList(groupIds));
					}
					inputStream = InputStreamUtil.getSuccessInputStream();
				} else {
					inputStream = InputStreamUtil.getFailedInputStream();
				}
			} else {
				inputStream = InputStreamUtil.getExistsInputStream();
			}
		}
		return SUCCESS;
	}

	@Action(value = "worker-delete", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "text/plain; charset=utf-8", "inputName",
			"inputStream" }) })
	public String delete() throws Exception {
		if (null != worker && null != worker.getWorkerId()) {
			boolean exists = workerService.exists(worker.getWorkerId());
			if (exists) {
				int delNum = workerService.delete(worker.getWorkerId());
				if (delNum == 1) {
					inputStream = InputStreamUtil.getSuccessInputStream();
				} else {
					inputStream = InputStreamUtil.getFailedInputStream();
				}
			} else {
				inputStream = InputStreamUtil.getNotExistsInputStream();
			}
		}
		return SUCCESS;
	}

	@Action(value = "worker-edit", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "text/plain; charset=utf-8", "inputName",
			"inputStream" }) })
	public String edit() throws Exception {
		if (null != worker && null != worker.getWorkerId()
				&& worker.getWorkerName() != null && null != worker.getEmail()) {
			boolean exists = workerService.exists(worker.getWorkerId());
			if (exists) {
				String passwd = worker.getPassword();
				if (StringUtils.isNotBlank(passwd)
						&& !StringUtils.equals(currentWorker.getPassword(),
								passwd)) {
					worker.setPassword(EncryptUtils.encryptPwd(passwd));
				}
				int count = workerService.update(worker);
				if (count >= 1) {
					List<Long> dbgIds = workerService
							.listGroupIdByWorkerId(currentWorker.getWorkerId());
					Long[] gIdss = CommonUtil.evalLongArray(groupIds);
					List<Long> addValues = CommonUtil.operatorAddValue(gIdss,
							dbgIds);
					List<Long> reduceValues = CommonUtil.operatorReduceValue(
							dbgIds, gIdss);
					if (!CollectionUtils.isEmpty(addValues)
							&& addValues.size() > 0) {
						workerService.insertWorkerOfGroups(
								currentWorker.getWorkerId(), addValues);
					}
					if (!CollectionUtils.isEmpty(reduceValues)
							&& reduceValues.size() > 0) {
						workerService.deleteWorkerOfGroups(
								currentWorker.getWorkerId(), reduceValues);
					}
					inputStream = InputStreamUtil.getSuccessInputStream();
				} else {
					inputStream = InputStreamUtil.getFailedInputStream();
				}
			} else {
				inputStream = InputStreamUtil.getNotExistsInputStream();
			}
		} else {
			inputStream = InputStreamUtil.getNotExistsInputStream();
		}
		return SUCCESS;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public Pager<Worker> getPager() {
		return pager;
	}

	public void setPager(Pager<Worker> pager) {
		this.pager = pager;
	}

	public Worker getWorker() {
		return worker;
	}

	public void setWorker(Worker worker) {
		this.worker = worker;
	}

	public void setWorkerService(WorkerService workerService) {
		this.workerService = workerService;
	}

	public void setParam(Map<String, String> param) {
		this.param = param;
	}

	public Map<String, String> getParam() {
		return param;
	}

	public void setDeptService(DeptService deptService) {
		this.deptService = deptService;
	}

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	public void setGroupIds(String[] groupIds) {
		this.groupIds = groupIds;
	}

}
